package com.yoo.module_base.extension

import android.net.Uri
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import com.yoo.module_base.utils.AppUtil

/**
 * @ClassName: ActivityExtension
 * @Description:
 * @Author: You
 */
var exitTime: Long = 0

/**
 * 退出APP
 * @param method 接受后续逻辑的方法参数
 */
fun AppCompatActivity.exitApp(method: (() -> Unit)? = null) {
    if (System.currentTimeMillis() - exitTime > 2000) {
        method?.invoke()
        exitTime = System.currentTimeMillis()
    } else {
        AppUtil.exitApp(this)
    }
}

/**
 * 线程切换
 */
inline fun runOnMain(crossinline block: () -> Unit) {
    if (Looper.myLooper() === Looper.getMainLooper()) {
        block()
    } else {
        Handler(Looper.getMainLooper()).post { block() }
    }
}

fun String.replaceParams(keyTitle: String, value: String?): String {
    val parseUri = Uri.parse(this)
    val urlBuildUpon = parseUri?.buildUpon()
    val key = parseUri?.getQueryParameter(keyTitle) ?: ""
    if (key.isBlank() && value.isNullOrBlank().not()) {
        return urlBuildUpon?.appendQueryParameter(keyTitle, value)?.build()?.toString() ?: ""
    }
    return this
}